package com.upnp.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.util.Xml;

public class EventOperate{
	private final String SUFFIX = "message";
	
	private Context 		m_con;
	private DBOpenHelper    m_db; 

	private Set<String> analyListID(String idList){
		String[] idArray = idList.split("_");
		Set<String> setID = new HashSet<String>();
		setID.clear();
		for(String id : idArray){
			setID.add(id);
		}
		if(setID.size()>0){
			return setID;
		}
		return null;
	}
	
	public EventOperate(int nType, Context con){
		this.m_con = con;
		this.m_db = new DBOpenHelper(nType, this.m_con);
	}
	
	public String GetSubjectListFromCurAccount(){
		String tagPath = null;
		try {
			if(!this.m_db.openAccountsDB()){
				Log.i("DB Operate", "Database open failed !~");
				return null;
			}
			this.m_db.setSubjectSQL();
			if(!this.m_db.execSQL(1)){
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		XMLCreateHelper xmlHelper = new XMLCreateHelper(this.m_con, this.m_db, SUFFIX);		
		tagPath = xmlHelper.writeSubjectToXML(this.m_db.getLocalEmailInfo());
		this.m_db.clearLocalEmailInfoList();
		this.m_con = null;
		this.m_db = null;
		xmlHelper = null;
		return tagPath;
	}
	
	public String  GetContactsFromEmail(){
		String tagPath = null;
		try {
			if(!this.m_db.openContactsDB()){	
				Log.i("DB Operate", "openContactsDB failed !~");
				return null;
			}
			this.m_db.setContactSQL();
			if(!this.m_db.execSQL(3)){
				Log.i("ExecSQL", "execSQL run failed!");
				return null;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		XMLCreateHelper xmlHelper = new XMLCreateHelper(this.m_con, this.m_db, SUFFIX);	
		tagPath = xmlHelper.writeContactToXML(this.m_db.getLocalEmailInfo());
		this.m_db.clearLocalEmailInfoList();
		this.m_con = null;
		this.m_db = null;
		xmlHelper = null;
		return tagPath;
	}
	
	public String GetEmailDetailsFromSubList(String aName, String idList){	
		String tagPath = null;
		Set<String> setID = analyListID(idList);
		if(analyListID(idList) == null){
			setID.clear();
			setID = null;
			return null;
		}
		if(this.m_db.openAccountsDB(aName)){
			this.m_db.setEmailSQL(setID);
			LocalEmailInfo localInfo = this.m_db.execSQL(aName);
			XMLCreateHelper xmlHelper = new XMLCreateHelper(this.m_con);		
			tagPath = xmlHelper.writeSubjectToXML(localInfo);
			localInfo = null;
			xmlHelper = null;
		}else{
			Log.i("DB Operate", "Database open failed !~");
			return null;
		}
		return tagPath;
	}
}

class DBOpenHelper{
	private final String CONTACT_NAME= "contacts";
	private final String ACCOUNT_DIR = "tb/accounts";
	private final String EMAIL_DIR   = "tb/emails";
	private final String CONTACT_DIR = "tb/contacts";
	private final String RELATE_DIR  = "tb/relateinfos";
	
	private Context 			 m_con;
	private String  			 m_dirAccount;     
	private String 				 SQL_QT;		
	private List<String> 		 m_aName; 
	private Cursor[]		     m_cursor;
	private SQLiteDatabase		 m_dbRes;
	private List<SQLiteDatabase> m_dbList;
	private List<LocalEmailInfo> m_emailInfo;
	
	public DBOpenHelper(int nType, Context con){
		if(0 == nType){
			this.m_con  = con;
			this.m_aName = new ArrayList<String>();
			this.m_dbList = new ArrayList<SQLiteDatabase>();
			this.m_emailInfo = new ArrayList<LocalEmailInfo>();		
			this.folderExists();
			this.getAccountListsPath();
		}else if(1 == nType){
			this.m_con  = con;
		}else if(2 == nType){
			this.m_con  = con;
			this.m_aName = new ArrayList<String>();
			this.m_dbList = new ArrayList<SQLiteDatabase>();
			this.m_emailInfo = new ArrayList<LocalEmailInfo>();	
			this.folderExists();
			this.getAccountListsPath();
		}else{
			Log.i("Error", "Parameter delivery error !~");
			return;	
		}
	}
	
	private boolean folderExists(){
		if(this.m_con == null){
			return false;
		}else{
			String dirPath = this.m_con.getFilesDir().getParentFile().getAbsolutePath();
			File[] files = {
					new File(dirPath, ACCOUNT_DIR),
					new File(dirPath, EMAIL_DIR),
					new File(dirPath, CONTACT_DIR),
					new File(dirPath, RELATE_DIR)
					};
			for(int i=0;i<files.length;i++){
				if(!files[i].exists()){
					files[i].mkdirs();
				}
			}		
			files 	= null;
			dirPath = null;
			return true;
		}
	}
	
	private void getAccountListsPath(){
		String dirPath = this.m_con.getFilesDir().getParentFile().getAbsolutePath();
		this.m_dirAccount = dirPath + File.separator + ACCOUNT_DIR;	
		File fAccounts = new File(this.m_dirAccount);
		File[] files = fAccounts.listFiles();
		for(int i=0;i<files.length;i++){
			this.m_aName.add(files[i].getName());
		}
		dirPath = null;
	}
	
	private void closeDB(SQLiteDatabase db){
		if(db.isOpen()){
			db.close();
			db = null;
		}
	}
	
	private void closeCursor(Cursor cursor){
		if(!cursor.isClosed()){
			cursor.close();
			cursor = null;
		}
	}
	
	public boolean openContactsDB(){
		String dbPath = this.m_con.getFilesDir().getAbsolutePath()
				.replace("files", "databases") + File.separator + CONTACT_NAME;
		File dbFile = new File(dbPath);
		if(!dbFile.exists()){
			Log.i(CONTACT_NAME, "Contacts is not found !~");
			dbFile = null;
			return false;
		}
		dbFile = null;
		SQLiteDatabase db = null;
		try {
			db = this.m_con.openOrCreateDatabase(dbPath, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.i("OpenContactDB", "Open databases failed !");
			e.printStackTrace();
		}
		if(null == db){
			Log.i("OpenContactDB", "Open databases failed !");
			return false;
		}
		this.m_dbList.add(db);
		return true;
	}
	
	public boolean openAccountsDB(){
		String dbName = null;
		String dbPath = this.m_con.getFilesDir().getAbsolutePath()
				.replace("files", "databases")+File.separator;
		for(String name:this.m_aName){
			dbName = name.split("\\.")[0] + ".db";
			SQLiteDatabase db = null;
			try {
				db = this.m_con.openOrCreateDatabase(dbPath+dbName, Context.MODE_PRIVATE, null);
			} catch (Exception e) {
				Log.i("OpenAccountDB", "Open databases failed !");
				e.printStackTrace();
			}
			if(null == db){
				return false;
			}
			this.m_dbList.add(db);
		}		
		return true;
	}
	
	public boolean openAccountsDB(String aName){
		String dbName = aName + ".db";
		String dbPath = this.m_con.getFilesDir().getAbsolutePath()
				.replace("files", "databases")+File.separator;
		try {
			this.m_dbRes = this.m_con.openOrCreateDatabase(dbPath+dbName, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
			Log.i("OpenAccountDB", "Open databases failed !");
			e.printStackTrace();
		}
		if(null == this.m_dbRes){
			return false;
		}
		return true;
	}
	
	public void setSubjectSQL(){
		
		this.SQL_QT = "select id, folder_id, uid, subject, sender_list, read, date" +
				" from messages where id is not null order by id asc";
	}
	
	public void setContactSQL(){
//		this.SQL_QT = "select to_list, cc_list, bcc_list from messages " + 
//					  "where to_list is not null group by to_list";
		this.SQL_QT = "select * from details where contact is not null";
	}
	
	public void setSubjectSQL(int readStatue){
		if(0 == readStatue || 1 == readStatue){
			this.SQL_QT = "select id, folder_id, uid, subject, sender_list, read, date " +
					"from messages where read = "
					+ readStatue +
					"and sender_list is not null order by id asc";
		}else{
			Log.i("Parameter error", "Status is only 0 or 1 ~~");
			return;
		}
	}
	
	public void setEmailSQL(Set<String> setID){
		String idArr = "";
		for(String id : setID){
			if(id.isEmpty()){
				continue;
			}else{
				idArr += id + ",";
			}
		}
		idArr = idArr.substring(0, idArr.length()-1);
		this.SQL_QT = "select id, folder_id, uid, subject, date, sender_list, to_list, cc_list, bcc_list, reply_to_list," +
			 "html_content, attachment_count, message_id, preview, mime_type, empty, read, flagged, answered, forwarded " +
			 "from messages where id in (" + idArr + ") order by id asc";
		idArr = null;
		setID.clear();
		setID = null;
	}
		
	public boolean execSQL(int type){
		if(this.m_aName.size()<=0){
			return false;
		}
		Cursor curCur = null;
		this.m_cursor = new Cursor[this.m_aName.size()];	
		if(1 == type){
			for(int i=0;i<this.m_cursor.length;i++){
				LocalEmailInfo localMsg = new LocalEmailInfo(1);
				this.m_cursor[i] = this.m_dbList.get(i).rawQuery(this.SQL_QT, new String[]{});
				curCur = this.m_cursor[i];
				while(curCur.moveToNext()){
					localMsg.saveEmailInfoToArray(curCur);
				}
				this.closeCursor(curCur);
				this.closeCursor(this.m_cursor[i]);
				this.closeDB(this.m_dbList.get(i));
				this.m_emailInfo.add(localMsg);
			}
		}else if(2 == type){
			for(int i=0;i<this.m_cursor.length;i++){
				LocalEmailInfo localMsg = new LocalEmailInfo(2);
				this.m_cursor[i] = this.m_dbList.get(i).rawQuery(this.SQL_QT, new String[]{});
				curCur = this.m_cursor[i];
				while(curCur.moveToNext()){
					localMsg.saveContactsToArray(curCur);
				}
				this.closeCursor(curCur);
				this.closeCursor(this.m_cursor[i]);
				this.closeDB(this.m_dbList.get(i));
				this.m_emailInfo.add(localMsg);
			}
		}else if(3 == type){
			this.m_cursor = new Cursor[1];
			LocalEmailInfo localMsg = new LocalEmailInfo(2);
			this.m_cursor[0] = this.m_dbList.get(0).rawQuery(this.SQL_QT, new String[]{});
			curCur = this.m_cursor[0];
			while(curCur.moveToNext()){
				localMsg.saveContactsToArray(curCur);
			}
			this.closeCursor(curCur);
			this.closeCursor(this.m_cursor[0]);
			this.closeDB(this.m_dbList.get(0));
			this.m_emailInfo.add(localMsg);
		}else{
			return false;
		}
		if(this.m_cursor.length>0){
			this.m_cursor = null;
		}
		if(this.m_dbList.size()>0){
			this.m_dbList.clear();
		}
		return true;
	}
	
	public LocalEmailInfo execSQL(String aName){
		LocalEmailInfo localMsg = new LocalEmailInfo(this.m_con);
		Cursor curCur = this.m_dbRes.rawQuery(this.SQL_QT, new String[]{});
		while(curCur.moveToNext()){
			localMsg.saveEmailInfoToArray(aName, curCur);
		}
		this.closeCursor(curCur);
		this.closeDB(this.m_dbRes);
		
		return localMsg;
	}
	
	public List<String> getAccountName(){
		return this.m_aName.size()>0?this.m_aName:null;
	}
	
	public List<LocalEmailInfo> getLocalEmailInfo(){
		return this.m_emailInfo.size()>0?this.m_emailInfo:null;
	}
	
	public SQLiteDatabase getDatabaseRes(){
		return this.m_dbRes;
	}
	
	public void clearLocalEmailInfoList(){
		this.m_emailInfo.clear();
	}
}

class XMLCreateHelper {
	private final String SUFFIX    = ".xml";
	private final String EMAIL_DIR = "tb/emails";
	private final String EMAIL_REL = "tb/relateinfos";
	private final String CONTACT   = "contacts.xml";
	private final String EMAIL_CON = "tb/contacts/contacts.xml";
	private final String XML_SUF   = "message_";
	private Context 			 m_com;
	private File[] 				 m_xmlFiles;
	private List<String> 		 m_xmlNameList;
	private List<LocalEmailInfo> m_emailInfo;
	
	public XMLCreateHelper(Context con){
		this.m_com = con;
	}
	
	public XMLCreateHelper(Context con, DBOpenHelper openHelp, String fileSuffix){
		this.m_com = con;
		this.m_xmlNameList = new ArrayList<String>();
		this.m_emailInfo = new ArrayList<LocalEmailInfo>();
		this.m_emailInfo.addAll(openHelp.getLocalEmailInfo());
		for(int i=0;i<m_emailInfo.size();i++){
			this.m_xmlNameList.add((openHelp.getAccountName().get(i)).split("\\.")[0]);
		}
		this.m_emailInfo.clear();
		String xmlPath = con.getFilesDir().getParent() + File.separator + EMAIL_DIR;
		m_xmlFiles = new File[this.m_xmlNameList.size()];
		for(int i=0;i<this.m_xmlNameList.size();i++){
			this.m_xmlFiles[i] = new File(xmlPath, this.m_xmlNameList.get(i)+"_"+fileSuffix+SUFFIX);
		}
		xmlPath = null;
	}
	
	public String writeSubjectToXML(LocalEmailInfo localMsg){
		FileOutputStream fos = null;
		XmlSerializer serializer = null;
		String aName = localMsg.getAccountName();
		String dbPath = this.m_com.getFilesDir().getParent() + File.separator + 
				EMAIL_REL + File.separator + aName + SUFFIX;
//		Log.i("Path", dbPath);
		File file = new File(dbPath);
		if(file.exists()){
			file.delete();
		}
		file = null;
		try {
			fos = new FileOutputStream(dbPath);	
		} catch (FileNotFoundException e) {
			Log.i("IOstreamError","File is not found !");
			e.printStackTrace();
		}
		serializer = Xml.newSerializer();	
		try {
			serializer.setOutput(fos, "utf-8");
			serializer.startDocument("utf-8", true);
			serializer.startTag(null, aName);
			for(int i=0;i<localMsg.getListSize();i++){
				serializer.startTag(null, XML_SUF+localMsg.getList_id().get(i).toString());
				serializer.startTag(null, "message");
				this.createChildNode(serializer, "aname", aName);
				this.createChildNode(serializer, "id", localMsg.getList_id().get(i).toString());	
				this.createChildNode(serializer, "uid", localMsg.getList_uid().get(i));	
				this.createChildNode(serializer, "subject", localMsg.getList_subject().get(i));
				this.createChildNode(serializer, "sender_list", localMsg.getList_sender_list().get(i));
				this.createChildNode(serializer, "to_list", localMsg.getList_to_list().get(i));
				this.createChildNode(serializer, "cc_list", localMsg.getList_cc_list().get(i));
				this.createChildNode(serializer, "bcc_list", localMsg.getList_bcc_list().get(i));
				this.createChildNode(serializer, "reply_to_list", localMsg.getList_reply_to_list().get(i));
				this.createChildNode(serializer, "preview", localMsg.getList_preview().get(i));
				this.createChildNode(serializer, "mime_type", localMsg.getList_mime_type().get(i));
				this.createChildNode(serializer, "message_id", localMsg.getList_message_id().get(i));
				this.createChildNode(serializer, "html_content", localMsg.getList_html_content().get(i));
				this.createChildNode(serializer, "date", localMsg.getList_date().get(i).toString());
				this.createChildNode(serializer, "read", localMsg.getList_read().get(i).toString());	
				this.createChildNode(serializer, "empty", localMsg.getList_empty().get(i).toString());
				this.createChildNode(serializer, "flagged", localMsg.getList_flagged().get(i).toString());
				this.createChildNode(serializer, "answered", localMsg.getList_answered().get(i).toString());
				this.createChildNode(serializer, "forwarded", localMsg.getList_forwarded().get(i).toString());
				this.createChildNode(serializer, "attachment_count", localMsg.getList_attachment_count().get(i).toString());
				this.createChildNode(serializer, "folder_id", localMsg.getList_folder_id().get(i).toString());			
				serializer.endTag(null, "message");
				serializer.startTag(null, "headers");
				for(Map.Entry<String, String> entry:localMsg.getList_headerContextLists().get(localMsg.getList_id().get(i)).entrySet()){
			    	this.createChildNode(serializer, entry.getKey(), entry.getValue());	
			    }
				serializer.endTag(null, "headers");		
				if(localMsg.getList_attachment_count().get(i) > 0 ){
					List<List <String>> tmpList = localMsg.getList_attchments().get(localMsg.getList_id().get(i));
					for(int size = 0;size<tmpList.get(0).size();size++){
						serializer.startTag(null, "attr_"+String.valueOf(size+1));	
						this.createChildNode(serializer, "id", tmpList.get(0).get(size));	
						this.createChildNode(serializer, "size", tmpList.get(1).get(size));	
						this.createChildNode(serializer, "name", tmpList.get(2).get(size));	
						this.createChildNode(serializer, "mime_type", tmpList.get(3).get(size));	
						this.createChildNode(serializer, "content_id", tmpList.get(4).get(size));
						this.createChildNode(serializer, "store_data", tmpList.get(5).get(size));	
						this.createChildNode(serializer, "content_uri", tmpList.get(6).get(size));	
						this.createChildNode(serializer, "content_disposition", tmpList.get(7).get(size));
						serializer.endTag(null, "attr_"+String.valueOf(size+1));
					}
					serializer.startTag(null, "attchment");	
					serializer.endTag(null, "attchment");
					localMsg.getList_attachment_count().clear();
				}
				serializer.endTag(null, XML_SUF+localMsg.getList_id().get(i).toString());
			}
			serializer.endTag(null, aName);
			serializer.endDocument();
			localMsg.getList_headerContextLists().clear();
			fos.flush();
			fos.close();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String tagPath  = "/relateinfos/" +  aName + SUFFIX;
		aName = null;
		dbPath = null;
		localMsg = null;

		return tagPath;
	}
	
	public String writeContactToXML(List<LocalEmailInfo> localMsgs){
		String xmlPathList = "";
		FileOutputStream fos = null;
		XmlSerializer serializer = null;
		Set<String> contacts = new HashSet<String>();
		for(String con : localMsgs.get(0).getContacts()){
			if(!con.isEmpty()){
				contacts.add(con);
			}
		}
		String contactFile = this.m_com.getFilesDir().getParent() + File.separator + EMAIL_CON;
		String curPath = contactFile;
		File file = new File(contactFile);
		if(file.exists()){
			file.delete();
		}
		try {
			fos = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			Log.i("IOstreamError","File is not found !");
			e.printStackTrace();
		}
		serializer = Xml.newSerializer();	
		try {
			serializer.setOutput(fos, "utf-8");
			serializer.startDocument("utf-8", true);
			serializer.startTag(null, CONTACT);
			for(String con : contacts){
				if(!con.isEmpty()){
					this.createChildNode(serializer, "contact", con);	
				}
			}
			serializer.endTag(null, CONTACT);
			serializer.endDocument();
			
			fos.flush();
			fos.close();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(localMsgs.size()>0){
			localMsgs.clear();
		}
		if(this.m_xmlNameList.size()>0){
			this.m_xmlNameList.clear();
		}
		if(this.m_xmlFiles.length>0){
			this.m_xmlFiles = null;
		}
		String ceptPath = curPath.split("tb/contacts")[1];
		String tagPath  = "/tb/contacts" +  ceptPath;
		xmlPathList = tagPath; 
		return xmlPathList;
	}
	
	public String writeSubjectToXML(List<LocalEmailInfo> localMsgs){
		String xmlPathList = "";
		FileOutputStream fos = null;
		XmlSerializer serializer = null;
		for(int fileIndex=0;fileIndex<this.m_xmlFiles.length;fileIndex++){
			String aName = (m_xmlFiles[fileIndex].getName()).split("_")[0];
			if(false == this.isExists(this.m_xmlFiles[fileIndex])){
				try {
					fos = new FileOutputStream(this.m_xmlFiles[fileIndex]);
				} catch (FileNotFoundException e) {
					Log.i("IOstreamError","File is not found !");
					e.printStackTrace();
				}
				serializer = Xml.newSerializer();	
				try {
					serializer.setOutput(fos, "utf-8");
					serializer.startDocument("utf-8", true);
					serializer.startTag(null, this.m_xmlNameList.get(fileIndex));
					for(int i=0;i<localMsgs.get(fileIndex).getListSize();i++){
						serializer.startTag(null, XML_SUF+localMsgs.get(fileIndex).getList_id().get(i).toString());
//						serializer.startTag(null, "message");
						serializer.attribute(null, "id", localMsgs.get(fileIndex).getList_id().get(i).toString());		
						this.createChildNode(serializer, "uid", localMsgs.get(fileIndex).getList_uid().get(i));	
						this.createChildNode(serializer, "subject", localMsgs.get(fileIndex).getList_subject().get(i));
						this.createChildNode(serializer, "sender_list", localMsgs.get(fileIndex).getList_sender_list().get(i));	
//						this.createChildNode(serializer, "reply_to_list", localMsgs.get(fileIndex).getList_reply_to_list().get(i));
						this.createChildNode(serializer, "date", localMsgs.get(fileIndex).getList_date().get(i).toString());
						this.createChildNode(serializer, "read", localMsgs.get(fileIndex).getList_read().get(i).toString());	
						this.createChildNode(serializer, "folder_id", localMsgs.get(fileIndex).getList_folder_id().get(i).toString());							
						this.createChildNode(serializer, "aname", aName);
//						serializer.endTag(null, "message");
						serializer.endTag(null, XML_SUF+localMsgs.get(fileIndex).getList_id().get(i).toString());
					}
					serializer.endTag(null, this.m_xmlNameList.get(fileIndex));
					serializer.endDocument();
					
					fos.flush();
					fos.close();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			String curPath  = this.m_xmlFiles[fileIndex].getAbsolutePath();
			String ceptPath = curPath.split("tb/emails")[1];
			String tagPath  = "/emails" +  ceptPath;
			xmlPathList += "<" + tagPath + ">";
			aName = null;
		}
		if(localMsgs.size()>0){
			localMsgs.clear();
		}
		if(this.m_xmlNameList.size()>0){
			this.m_xmlNameList.clear();
		}
		if(this.m_xmlFiles.length>0){
			this.m_xmlFiles = null;
		}
		return xmlPathList;
	}
	
	public void createChildNode(XmlSerializer serializer, String name, String text){
		try {
			serializer.startTag(null, name);
			serializer.text(text);
			serializer.endTag(null, name);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isExists(File file){
		if(file.exists()){
			return true;
		}else{
			return false;
		}
	}
}

class LocalEmailInfo{
	private Context  			m_con;
	private String              m_aName;
	
	private List<Long> 			list_date;
	private List<Integer> 		list_id;
	private List<Integer> 		list_read;
	private List<Integer> 		list_empty;
	private List<Integer> 		list_flagged;
	private List<Integer> 		list_answered;
	private List<Integer> 		list_forwarded;
	private List<Integer> 		list_folder_id;
	private List<Integer> 		list_attachment_count;
	private List<String>  		list_uid;	
	private List<String>  		list_to_list;
	private List<String>  		list_cc_list;
	private List<String>  		list_subject;
	private List<String>  		list_preview;
	private List<String>  		list_bcc_list;
	private List<String>  		list_mime_type;
	private List<String>  		list_message_id;
	private List<String>  		list_sender_list;
	private List<String>  		list_html_content;
	private List<String>  		list_reply_to_list;
	private List<String>    	list_attchment_id;
	private List<String>    	list_attchment_size;
	private List<String>  		list_attchment_name;
	private List<String>  		list_attchment_mime_type;
	private List<String>  		list_attchment_content_id;
	private List<String>  		list_attchment_store_data;
	private List<String>  		list_attchment_content_uri;
	private List<String>  		list_attchment_content_disposition;
	
	private Set<String> 								 contacts;
	private IdentityHashMap<String, String> 			 headerContexts;
	private List<List <String>>    				 		 list_attchmentInfo;
	private IdentityHashMap<Integer,List<List <String>>> list_attchments;
	private Map<Integer, IdentityHashMap<String, String>>list_headerContexts;
	
	public LocalEmailInfo(int type) {
		if(1 == type){
			list_id 		 	  = new ArrayList<Integer>();
			list_read		 	  = new ArrayList<Integer>();
			list_folder_id 	 	  = new ArrayList<Integer>();
			list_date 		 	  = new ArrayList<Long>();
			list_uid	     	  = new ArrayList<String>();
			list_subject 	 	  = new ArrayList<String>();
			list_sender_list 	  = new ArrayList<String>();
			list_reply_to_list    = new ArrayList<String>();
		}else if(2 == type){
			contacts              = new HashSet<String>();
		}else{
			return;
		}
	}
	
	public LocalEmailInfo(Context con) {
		m_con			      = con;
		list_id 		 	  = new ArrayList<Integer>();
		list_read		 	  = new ArrayList<Integer>();
		list_date 		 	  = new ArrayList<Long>();
		list_empty		      = new ArrayList<Integer>();
		list_flagged   		  = new ArrayList<Integer>();
		list_answered   	  = new ArrayList<Integer>();
		list_forwarded   	  = new ArrayList<Integer>();
		list_folder_id 	 	  = new ArrayList<Integer>();
		list_attachment_count = new ArrayList<Integer>();
		list_uid	     	  = new ArrayList<String>();
		list_subject 	 	  = new ArrayList<String>();
		list_to_list 	 	  = new ArrayList<String>();
		list_cc_list 	 	  = new ArrayList<String>();
		list_preview 	 	  = new ArrayList<String>();
		list_bcc_list 	 	  = new ArrayList<String>();
		list_mime_type 	 	  = new ArrayList<String>();
		list_message_id 	  = new ArrayList<String>();
		list_sender_list      = new ArrayList<String>();
		list_html_content	  = new ArrayList<String>();
		list_reply_to_list    = new ArrayList<String>();
		list_attchments       = new IdentityHashMap<Integer,List<List <String>>>();
		list_headerContexts   = new HashMap<Integer, IdentityHashMap<String,String>>();
	}

	public int getListSize() {
		return this.list_id.size()>0?this.list_id.size():0;
	}
	
	public String getAccountName(){
		return this.m_aName;
	}

	public List<Integer> getList_id() {
		return list_id;
	}

	public void setList_id(int id) {
		this.list_id.add(id>0?id:0);
	}

	public List<Integer> getList_read() {
		return list_read;
	}

	public void setList_read(int read) {
		this.list_read.add(read);
	}

	public List<Integer> getList_folder_id() {
		return list_folder_id;
	}

	public void setList_folder_id(int folder_id) {
		this.list_folder_id.add(folder_id>0?folder_id:0);
	}

	public List<Long> getList_date() {
		return list_date;
	}

	public void setList_date(Long list_date) {
		this.list_date.add(String.valueOf(list_date).length()>0?list_date:0);
	}

	public List<String> getList_uid() {
		return list_uid;
	}

	public void setList_uid(String uid) {
		this.list_uid.add(uid);
	}

	public List<String> getList_subject() {
		return list_subject;
	}

	public void setList_subject(String subject) {
		this.list_subject.add(subject);
	}

	public List<String> getList_sender_list() {
		return list_sender_list;
	}
	public void setList_sender_list(String sender_list) {
		String curSenderList = sender_list.length()>0?sender_list:"NULL";
		if(curSenderList.equals("NULL")){
			this.list_sender_list.add("NULL");
		}else{
			String[] senderList = curSenderList.split("\\;");
			this.list_sender_list.add(senderList[0]);
		}
	}
	
	public List<Integer> getList_empty() {
		return list_empty;
	}

	public void setList_empty(int list_empty) {
		this.list_empty.add(list_empty);
	}

	public List<Integer> getList_flagged() {
		return list_flagged;
	}

	public void setList_flagged(int list_flagged) {
		this.list_flagged.add(list_flagged);
	}

	public List<Integer> getList_answered() {
		return list_answered;
	}

	public void setList_answered(int list_answered) {
		this.list_answered.add(list_answered);
	}

	public List<Integer> getList_forwarded() {
		return list_forwarded;
	}

	public void setList_forwarded(int list_forwarded) {
		this.list_forwarded.add(list_forwarded);
	}

	public List<Integer> getList_attachment_count() {
		return list_attachment_count;
	}

	public void setList_attachment_count(int list_attachment_count) {
		this.list_attachment_count.add(list_attachment_count);
	}

	public List<String> getList_to_list() {
		return list_to_list;
	}

	public void setList_to_list(String list_to_list) {
		String curToList = list_to_list.length()>0?list_to_list:"NULL";
		if(curToList.equals("NULL")){
			this.list_to_list.add("NULL");
		}else{
			String[] listArr = curToList.split("\\;");
			this.list_to_list.add(listArr[0]);
		}
	}

	public List<String> getList_cc_list() {
		return list_cc_list;
	}

	public void setList_cc_list(String list_cc_list) {
		String curToList = list_cc_list.length()>0?list_cc_list:"NULL";
		if(curToList.equals("NULL")){
			this.list_cc_list.add("NULL");
		}else{
			String[] listArr = curToList.split("\\;");
			this.list_cc_list.add(listArr[0]);
		}
	}
	
	public List<String> getList_bcc_list() {
		return list_bcc_list;
	}

	public void setList_bcc_list(String list_bcc_list) {
		String curToList = list_bcc_list.length()>0?list_bcc_list:"NULL";
		if(curToList.equals("NULL")){
			this.list_bcc_list.add("NULL");
		}else{
			String[] listArr = curToList.split("\\;");
			this.list_bcc_list.add(listArr[0]);
		}
	}

	public List<String> getList_preview() {
		return list_preview;
	}

	public void setList_preview(String list_preview) {
		this.list_preview.add(list_preview);
	}

	public List<String> getList_mime_type() {
		return list_mime_type;
	}

	public void setList_mime_type(String list_mime_type) {
		this.list_mime_type.add(list_mime_type);
	}

	public List<String> getList_message_id() {
		return list_message_id;
	}

	public void setList_message_id(String list_message_id) {
		this.list_message_id.add(list_message_id);
	}

	public List<String> getList_html_content() {
		return list_html_content;
	}

	public void setList_html_content(String list_html_content) {
		this.list_html_content.add(list_html_content);
	}

	public List<String> getList_reply_to_list() {
		return list_reply_to_list;
	}

	public void setList_reply_to_list(String list_reply_to_list) {
		String curReply = list_reply_to_list.length()>0?list_reply_to_list:"NULL";
		if(curReply.equals("NULL")){
			this.list_reply_to_list.add(list_reply_to_list);
		}else{
			String[] listArr = curReply.split("\\;");
			this.list_reply_to_list.add(listArr[0]+";");
			listArr = null;
		}
	}
	
	public void setContacts(String contact){
		String curContact = contact.length()>0?contact:"NULL";
		if(curContact.equals("NULL")){
			return;
		}else{
			String[] listArr = curContact.split("\\;");
			this.contacts.add(listArr[0]+";");
		}
	}
	
	public Set<String> getContacts(){
		return this.contacts;
	}
	
	public IdentityHashMap<Integer,List<List <String>>> getList_attchments(){
		return this.list_attchments;
	}
	
	public IdentityHashMap<String, String> getList_headerContexts(){
		return this.headerContexts;
	}
	
	public  Map<Integer, IdentityHashMap<String, String>> getList_headerContextLists(){
		return this.list_headerContexts;
	}

	public void saveCurrentEmailOtherInfos(int id, int attachment_count, Context con){
		if(id <= 0){
			return;
		}	
		this.headerContexts = new IdentityHashMap<String, String>(); 
		this.headerContexts.clear();
		String dbPath = con.getFilesDir().getAbsolutePath().replace("files", "databases")
				+ File.separator + this.m_aName + ".db";
		SQLiteDatabase db = null;
		try {
			db = con.openOrCreateDatabase(dbPath, Context.MODE_PRIVATE, null);
			String SQL = "select name, value from headers where message_id = ?";
			Cursor curCur = db.rawQuery(SQL, new String[]{String.valueOf(id)});
			while(curCur.moveToNext()){
				this.headerContexts.put(curCur.getString(curCur.getColumnIndex("name")), curCur.getString(curCur.getColumnIndex("value")));
			}
			curCur.close();
			this.list_headerContexts.put(id, this.headerContexts);
			SQL = "select count(message_id)from attachments where message_id = ?";
			curCur = db.rawQuery(SQL, new String[]{String.valueOf(id)});
			this.list_attchments.clear();
			while(curCur.moveToNext()){
				if(curCur.getInt(curCur.getColumnIndex("count(message_id)")) > 0){
					list_attchment_id.clear();
					list_attchment_size.clear();
					list_attchment_name.clear();
					list_attchment_mime_type.clear();
					list_attchment_content_id.clear();
					list_attchment_store_data.clear();
					list_attchment_content_uri.clear();
					list_attchment_content_disposition.clear();
					
					list_attchment_id 				   = new ArrayList<String>();
					list_attchment_size 			   = new ArrayList<String>();
					list_attchment_name 			   = new ArrayList<String>();
					list_attchment_mime_type 		   = new ArrayList<String>();
					list_attchment_content_id 		   = new ArrayList<String>();
					list_attchment_store_data 		   = new ArrayList<String>();
					list_attchment_content_uri 		   = new ArrayList<String>();
					list_attchment_content_disposition = new ArrayList<String>();	
					
					list_attchmentInfo = new ArrayList<List <String>>();
					String sql = "select * from attachments where message_id = ?";
					Cursor curcur = db.rawQuery(sql, new String[]{String.valueOf(id)});
					while(curcur.moveToNext()){
						list_attchment_id.add(curcur.getString(curcur.getColumnIndex("id")));
						list_attchment_size.add(curcur.getString(curcur.getColumnIndex("size")));
						list_attchment_name.add(curcur.getType(curcur.getColumnIndex("name")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("name")));
						list_attchment_mime_type.add(curcur.getType(curcur.getColumnIndex("mime_type")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("mime_type")));
						list_attchment_content_id.add(curcur.getType(curcur.getColumnIndex("content_id")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("content_id")));
						list_attchment_store_data.add(curcur.getType(curcur.getColumnIndex("store_data")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("store_data")));
						list_attchment_content_uri.add(curcur.getType(curcur.getColumnIndex("content_uri")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("content_uri")));
						list_attchment_content_disposition.add(curcur.getType(curcur.getColumnIndex("content_disposition")) == Cursor.FIELD_TYPE_NULL?"NULL":curcur.getString(curcur.getColumnIndex("content_disposition")));
					}
					list_attchmentInfo.add(list_attchment_id);
					list_attchmentInfo.add(list_attchment_size);
					list_attchmentInfo.add(list_attchment_name);
					list_attchmentInfo.add(list_attchment_mime_type);
					list_attchmentInfo.add(list_attchment_content_id);
					list_attchmentInfo.add(list_attchment_store_data);
					list_attchmentInfo.add(list_attchment_content_uri);
					list_attchmentInfo.add(list_attchment_content_disposition);
					this.list_attchments.put(id, list_attchmentInfo);
					curcur.close();
				}else{
					this.list_attchments.put(id, null);
				}
			}
			curCur.close();
			db.close();
		} catch (Exception e) {
			Log.i("DatabasesError", "Open Databases failed !~");
			e.printStackTrace();
		}
		dbPath = null;
	}
	
//	public void saveContactsToArray(Cursor cursor){
//		String[] colums = {
//				"to_list", 
//				"cc_list", 
//				"bcc_list"};
//		String contact = null;
//		for(int i=0;i<colums.length;i++){
//			contact = cursor.getString(cursor.getColumnIndex(colums[i]));
//			if(contact.length()>0){
//				this.setContacts(contact);
//			}
//		}
//		contact = null;
//	}
	
	public void saveContactsToArray(Cursor cursor){
		String contact = null;
		contact = cursor.getString(cursor.getColumnIndex("contact"));
		if(contact.length()>0){
			this.setContacts(contact);
		}
		contact = null;
	}
	
	public void saveEmailInfoToArray(Cursor cursor){
		this.setList_id(cursor.getType(cursor.getColumnIndex("id"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("id")));
		this.setList_read(cursor.getType(cursor.getColumnIndex("read"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("read")));
		this.setList_folder_id(cursor.getType(cursor.getColumnIndex("folder_id"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("folder_id")));
		this.setList_date(cursor.getType(cursor.getColumnIndex("date"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getLong(cursor.getColumnIndex("date")));
		this.setList_uid(cursor.getType(cursor.getColumnIndex("uid"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("uid")));
		this.setList_subject(cursor.getType(cursor.getColumnIndex("subject"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("subject")));
		this.setList_sender_list(cursor.getType(cursor.getColumnIndex("sender_list"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("sender_list")));
//		String from = cursor.getString(cursor.getColumnIndex("reply_to_list"));
//		if(from.length()>0){
//			this.setList_reply_to_list(from);
//		}else{
//			this.setList_reply_to_list("NULL");
//		}
//		from = null;
	}
	
	public void saveEmailInfoToArray(String aname, Cursor cursor){
		this.m_aName = aname;
		this.setList_id(cursor.getType(cursor.getColumnIndex("id"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("id")));
		this.setList_read(cursor.getType(cursor.getColumnIndex("read"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("read")));
		this.setList_folder_id(cursor.getType(cursor.getColumnIndex("folder_id"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("folder_id")));
		this.setList_date(cursor.getType(cursor.getColumnIndex("date"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getLong(cursor.getColumnIndex("date")));
		this.setList_uid(cursor.getType(cursor.getColumnIndex("uid"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("uid")));
		this.setList_subject(cursor.getType(cursor.getColumnIndex("subject"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("subject")));
		this.setList_sender_list(cursor.getType(cursor.getColumnIndex("sender_list"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("sender_list"))); 
		this.setList_empty(cursor.getType(cursor.getColumnIndex("empty"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("empty")));
		this.setList_flagged(cursor.getType(cursor.getColumnIndex("flagged"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("flagged")));
		this.setList_answered(cursor.getType(cursor.getColumnIndex("answered"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("answered")));
		this.setList_forwarded(cursor.getType(cursor.getColumnIndex("forwarded"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("forwarded")));
		this.setList_attachment_count(cursor.getType(cursor.getColumnIndex("attachment_count"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("attachment_count")));
		this.setList_to_list(cursor.getType(cursor.getColumnIndex("to_list"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("to_list")));
		this.setList_cc_list(cursor.getType(cursor.getColumnIndex("cc_list"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("cc_list")));
		this.setList_bcc_list(cursor.getType(cursor.getColumnIndex("bcc_list"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("bcc_list")));
		this.setList_preview(cursor.getType(cursor.getColumnIndex("preview"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("preview")));
		this.setList_mime_type(cursor.getType(cursor.getColumnIndex("mime_type"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("mime_type")));
		this.setList_message_id(cursor.getType(cursor.getColumnIndex("message_id"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("message_id")));
		this.setList_html_content(cursor.getType(cursor.getColumnIndex("html_content"))==Cursor.FIELD_TYPE_NULL?"NULL":cursor.getString(cursor.getColumnIndex("html_content")));
		
		String from = cursor.getString(cursor.getColumnIndex("reply_to_list"));
		if(from.length()>0){
			this.setList_reply_to_list(from);
		}else{
			this.setList_reply_to_list("NULL");
		}
		from = null;
		
		this.saveCurrentEmailOtherInfos(cursor.getType(cursor.getColumnIndex("id"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("id")), 
				cursor.getType(cursor.getColumnIndex("attachment_count"))==Cursor.FIELD_TYPE_NULL?-1:cursor.getInt(cursor.getColumnIndex("attachment_count")), this.m_con);
	}
	
}
